package service

import (
    "context"
    "gitee.com/WisdomClassroom/CollegeStruct/glb"
    "gitee.com/WisdomClassroom/core"
    "gitee.com/WisdomClassroom/core/models"
    "gitee.com/WisdomClassroom/core/protobufs/v1/pb"
    "github.com/jinzhu/gorm"
)

func (s *Service) ListCollege(_ context.Context, in *pb.ListCollegeRequest) (*pb.ListCollegeResponse, error) {
    token := core.NewToken()
    err := token.UnpackToken(in.AuthToken, &core.FlagTokenCert)
    if err != nil {
        return &pb.ListCollegeResponse{Status: &pb.ResponseStatus{
            Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
        },}, nil
    }

    var colleges []models.CollegeModel
    err = glb.DB.Scopes(notDeleted).Find(&colleges).Error
    if err != nil && err != gorm.ErrRecordNotFound {
        glb.Logger.Error(err.Error())
        return listCollegeRespSvrErr, nil
    }

    var collegeMngrBinds []models.CollegeManagerBindModel
    err = glb.DB.Scopes(notDeleted).Find(&collegeMngrBinds).Error
    if err != nil && err != gorm.ErrRecordNotFound {
        glb.Logger.Error(err.Error())
        return listCollegeRespSvrErr, nil
    }

    listCollegeRespUnitsMap := make(map[string]*pb.ListCollegeResponseUnit)

    for _, college := range colleges {
        listCollegeRespUnitsMap[college.UUID] = &pb.ListCollegeResponseUnit{
            UUID:        college.UUID,
            Name:        college.Name,
            Description: college.Description,
        }
    }
    for _, collegeMngrBind := range collegeMngrBinds {
        listCollegeRespUnitsMap[collegeMngrBind.CollegeUUID].ManagerUUID =
            append(listCollegeRespUnitsMap[collegeMngrBind.CollegeUUID].ManagerUUID, collegeMngrBind.ManagerUUID)
    }

    var listCollegeResponseUnits []*pb.ListCollegeResponseUnit
    for _, listCollegeResponseUnit := range listCollegeRespUnitsMap {
        listCollegeResponseUnits = append(listCollegeResponseUnits, listCollegeResponseUnit)
    }
    return &pb.ListCollegeResponse{
        Status:   &pb.ResponseStatus{Code: pb.ResponseStatusCode_Suc},
        Colleges: listCollegeResponseUnits,
    }, nil
}
